<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="css/login.css">
</head>
<body>
    <div class="container">
        <div class="login">
            <h2>注 册</h2>
            <input type="text" name="username" placeholder="用户名" id="username" />
            <input type="password" name="password" placeholder="密码" id="password" />
            <button type="submit" id="submit">注册</button>
        </div>
    </div>

    <!-- 引入 jquery -->
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <!-- 实现前后端交互 -->
    <script>
        let submitButton = document.querySelector('#submit');
        submitButton.onclick = function() {
            // 1. 获取到用户输入的用户名和密码
            let username = document.querySelector('#username').value;
            let password = document.querySelector('#password').value;
            if (username == '' || password == '') {
                alert('您输入的用户名或密码为空!');
                return;
            }

            // 2. 发送 ajax 请求
            $.ajax({
                type: 'post',
                url: '/register',
                data: {
                    username: username,
                    password: password
                },
                success: function(body) {
                    if (body && body.userId > 0) {
                        alert('注册成功! 将跳转到登录页面!');
                        location.assign('/login.html');
                    } else {
                        alert('注册失败!');
                    }
                }
            });
        }

        // 回车事件
        $(document).ready(function () {
            $(".login input").keydown(function (event) {
                if (event.keyCode == 13) {
                    let loginButton = document.querySelector('.login button');
                    loginButton.click();
                }
            });
        });
    </script>
</body>
</html>